<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="queryParams.userType" placeholder="请选择用户类型" clearable size="small">
          <el-option
            v-for="dict in userTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>-->
      <el-form-item label="机构" prop="institutionId" v-if="admin">
        <el-select v-model="queryParams.deptId" placeholder="请选择机构" clearable size="small" @change="selectClass">
          <el-option
            v-for="dept in deptList"
            :key="dept.institutionId"
            :label="dept.institutionName"
            :value="dept.institutionId"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="年级" prop="gradeId">
        <el-input
          v-model="queryParams.gradeId"
          placeholder="请输入年级ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="班级" prop="classId" v-if="admin">
        <el-select v-model="queryParams.classId" placeholder="请选择班级" clearable size="small">
          <el-option
            v-for="dept in classList"
            :key="dept.classId"
            :label="dept.className"
            :value="dept.classId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="searchTime">
        <el-date-picker
          v-model="queryParams.searchTime"
          type="month"
          placeholder="选择月">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tongban:sign:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="signList" @selection-change="handleSelectionChange" border>
      <el-table-column label="名称" align="center" prop="userName" fixed/>
      <!--<el-table-column label="类型" align="center" prop="userType" :formatter="userTypeFormat" fixed/>-->
      <el-table-column label="机构" align="center" prop="deptName" fixed/>
      <el-table-column label="年级" align="center" prop="gradeName" fixed/>
      <el-table-column label="班级" align="center" prop="className" fixed/>
<!--      <el-table-column label="人脸识别照片" align="center" prop="image" fixed>
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.image"
            :preview-src-list='[scope.row.image]'>
          </el-image>
        </template>
      </el-table-column>-->
      <el-table-column align="center" v-for="col in cols" prop="111" :label="col.label" :formatter="formatContent" min-width="120px"/>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="false">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tongban:sign:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tongban:sign:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listSign, getSign, delSign, addSign, updateSign, exportSign } from "@/api/tongban/sign";
import { listInstitutionData } from "@/api/tongban/institution";
import { listInstitutionClass } from "@/api/tongban/class";
import { getInfo } from '@/api/login'
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "Sign",
  components: {
    ImageUpload,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      userTypeOptions:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 考勤记录表格数据
      signList: [],
      deptList: [],
      classList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      admin: false,
      cols:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        userType: null,
        signIn: null,
        signOut: null,
        year: null,
        month: null,
        day: null,
        deptId: null,
        deptName: null,
        gradeId: null,
        gradeName: null,
        classId: null,
        className: null,
        image: null,
        searchTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("user_type").then(response => {
      this.userTypeOptions = response.data;
    });
    listInstitutionData().then(res => {
      this.deptList = res.data;
    })
    this.isAdmin();
  },
  methods: {
    /** 查询考勤记录列表 */
    getList() {
      let str = this.queryParams.searchTime;
      if(!str || str == "undefined" || str == "null"){
        this.queryParams.searchTime = new Date();
      }

      try{
        console.log(this.queryParams.searchTime)
        let tYear = this.queryParams.searchTime.getFullYear();
        let tMonth = this.queryParams.searchTime.getMonth() + 1;
        if(tMonth.toString().length == 1){
          tMonth = "0" + tMonth;
        }
        this.queryParams.searchTime = tYear + "-" + tMonth;
      } catch(err) {
        console.log(err)
        //在此处理错误
      }

      this.loading = true;
      listSign(this.queryParams).then(response => {
        this.signList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.getDaysOfMonth();
    },
    formatContent(row, column, cellValue, index){//获取签到时间和签退时间展示\
      //获取标签上面day内容
      let day = column.label.split("/")[0] - 1;
      let data = row.signListData;

      return data[day].value;
    },
    isAdmin(){
      getInfo().then(response => {
        if(response.user.userId == 1){
          this.admin = true;
        }
      });
    },
    selectClass(id){
      listInstitutionClass(id).then(res => {
        this.classList = res.data;
        //this.form.classId = this.classList[0];
      })
    },
    userTypeFormat(row) {
      return this.selectDictLabel(this.userTypeOptions, row.userType);
    },
    getDaysOfMonth(year, month){
      this.cols = [];
      let myDate = new Date();
      let tYear = myDate.getFullYear();
      let tMonth = myDate.getMonth() + 1;
      let date = new Date(tYear, tMonth,0);
      let days = date.getDate();
      for(let i = 1; i<=days; i++){
        let label = i + "/" + tMonth;
        this.cols.push({label: label});
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recordId: null,
        userId: null,
        userName: null,
        userType: null,
        signIn: null,
        signOut: null,
        year: null,
        month: null,
        day: null,
        createTime: null,
        deptId: null,
        deptName: null,
        gradeId: null,
        gradeName: null,
        classId: null,
        className: null,
        image: null,
        signListData: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recordId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考勤记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recordId = row.recordId || this.ids
      getSign(recordId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考勤记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.recordId != null) {
            updateSign(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSign(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recordIds = row.recordId || this.ids;
      this.$confirm('是否确认删除考勤记录编号为"' + recordIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSign(recordIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有考勤记录数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSign(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
